<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        @submit.native.prevent
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="65px"
      >
        <el-form-item label="场景名称" prop="messageSceneName">
          <common-input
            v-model="queryParams.messageSceneName"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
      </el-form>
    </common-search>
    <common-table slot="content" v-loading="loading" :data="sceneList">
      <el-table-column
        label="场景编码"
        align="left"
        prop="messageSceneCode"
        show-overflow-tooltip
      />
      <el-table-column
        label="场景名称"
        align="left"
        prop="messageSceneName"
        show-overflow-tooltip
      />
      <el-table-column label="通知方式" align="left" width="180px">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.email === 0"
            style="margin-right: 8px"
            type="danger"
            >邮件
          </el-tag>
          <el-tag
            type="warning"
            v-if="scope.row.sms === 0"
            style="margin-right: 8px"
            >短信
          </el-tag>
          <el-tag
            type="success"
            v-if="scope.row.sysmsg === 0"
            style="margin-right: 8px"
            >系统
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="left" width="90px">
        <template slot-scope="scope">
          <el-button type="text" @click="showInfoDialog(scope.row)"
            >详情
          </el-button>
          <el-button type="text" @click="showEditDialog(scope.row)"
            >编辑
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <common-info-dialog
      :visible.sync="isInfoDialog"
      @cancel="isInfoDialog = false"
      title="通知方式详情"
    >
      <common-info-table>
        <common-info-table-cell label="场景编码"
          >{{ info.messageSceneCode }}
        </common-info-table-cell>
        <common-info-table-cell label="场景名称"
          >{{ info.messageSceneName }}
        </common-info-table-cell>
        <common-info-table-cell label="通知方式"
          >{{ info.mode }}
        </common-info-table-cell>
        <common-info-table-cell label="短信模板编码" v-if="info.sms === 0"
          >{{ info.smsTemplateCode }}
        </common-info-table-cell>
        <common-info-table-cell label="短信模板名称" v-if="info.sms === 0"
          >{{ info.smsTemplateName }}
        </common-info-table-cell>
        <common-info-table-cell label="邮件模板编码" v-if="info.email === 0"
          >{{ info.emailTemplateCode }}
        </common-info-table-cell>
        <common-info-table-cell label="邮件模板名称" v-if="info.email === 0"
          >{{ info.emailTemplateName }}
        </common-info-table-cell>
        <template v-if="info.isSysMsgTemplate">
          <common-info-table-cell label="系统模板编码" v-if="info.sysmsg === 0"
            >{{ info.sysmsgTemplateCode }}
          </common-info-table-cell>
          <common-info-table-cell label="系统模板名称" v-if="info.sysmsg === 0"
            >{{ info.sysmsgTemplateName }}
          </common-info-table-cell>
        </template>
        <common-info-table-cell label="场景描述"
          >{{ info.messageSceneRemark }}
        </common-info-table-cell>
      </common-info-table>
    </common-info-dialog>

    <common-edit-dialog
      title="编辑通知方式"
      :visible.sync="open"
      @cancel="cancel"
      @submit="submitForm"
      :button-loading="isPersistenceLoading"
    >
      <el-form
        ref="form"
        v-if="open"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-row :gutter="18">
          <el-col :span="24">
            <el-form-item label="场景编码" prop="messageSceneCode">
              <common-input
                v-model="form.messageSceneCode"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="场景名称" prop="messageSceneName">
              <common-input
                v-model="form.messageSceneName"
                placeholder="请输入"
                :maxlength="32"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="短信通知" prop="sms">
              <el-radio-group v-model="form.sms" @change="smsChange">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="短信模板" prop="smsTemplateCode">
              <el-select
                v-model="form.smsTemplateCode"
                placeholder="请选择"
                style="width: calc(100% - 100px)"
                :disabled="form.sms === 0 ? false : 'disabled'"
              >
                <el-option
                  v-for="item in smsTemplate"
                  :key="item.id"
                  :label="item.name"
                  :value="item.code"
                >
                </el-option>
              </el-select>
              <el-button
                :disabled="form.sms === 0 ? false : 'disabled'"
                type="primary"
                style="margin-left: 8px"
                @click="showSmsTemplate"
                plain
                >查看模板
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="邮件通知" prop="email">
              <el-radio-group v-model="form.email" @change="emailChange">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="邮件模板" prop="emailTemplateCode">
              <el-select
                v-model="form.emailTemplateCode"
                placeholder="请选择"
                style="width: calc(100% - 100px)"
                :disabled="form.email === 0 ? false : 'disabled'"
              >
                <el-option
                  v-for="item in emailTemplate"
                  :key="item.id"
                  :label="item.name"
                  :value="item.code"
                >
                </el-option>
              </el-select>
              <el-button
                :disabled="form.email === 0 ? false : 'disabled'"
                type="primary"
                style="margin-left: 8px"
                @click="showEmailTemplate"
                plain
                >查看模板
              </el-button>
            </el-form-item>
          </el-col>

          <template v-if="form.isSysMsgTemplate">
            <el-col :span="24">
              <el-form-item label="系统通知" prop="sysmsg">
                <el-radio-group v-model="form.sysmsg" @change="sysChange">
                  <el-radio :label="0">是</el-radio>
                  <el-radio :label="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="系统模板" prop="sysmsgTemplateCode">
                <el-select
                  v-model="form.sysmsgTemplateCode"
                  placeholder="请选择"
                  style="width: calc(100% - 100px)"
                  :disabled="form.sysmsg === 0 ? false : 'disabled'"
                >
                  <el-option
                    v-for="item in sysTemplate"
                    :key="item.id"
                    :label="item.name"
                    :value="item.code"
                  >
                  </el-option>
                </el-select>
                <el-button
                  :disabled="form.sysmsg === 0 ? false : 'disabled'"
                  type="primary"
                  style="margin-left: 8px"
                  @click="showSysTemplate"
                  >查看模板
                </el-button>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="24">
            <el-form-item label="场景描述" prop="messageSceneRemark">
              <common-input
                type="textarea"
                v-model="form.messageSceneRemark"
                placeholder="请输入"
              ></common-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </common-edit-dialog>

    <common-info-dialog
      :title="`${templateTitle}模板内容`"
      :visible.sync="isTemplateDialog"
      @cancel="isTemplateDialog = false"
    >
      <common-info-table>
        <common-info-table-cell label="模板名称"
          >{{ templateInfo.name }}
        </common-info-table-cell>
        <common-info-table-cell label="模板主题"
          >{{ templateInfo.subject }}
        </common-info-table-cell>
        <common-info-table-cell label="模板内容">
          <span v-html="templateInfo.content"></span>
        </common-info-table-cell>
      </common-info-table>
    </common-info-dialog>
  </common-list>
</template>

<script>
import { queryMessageListByPage, updateMessageScene } from "@/api/system/scene";
import { getTemplate as getEmailTemplate } from "@/api/system/emailtemplate";
import { getTemplate as getSmsTemplate } from "@/api/system/msgtemplate";
import { getTemplate as getSysTemplate } from "@/api/system/template";
import InfoTable from "@/components/InfoTable";
import BaseList from "@/mixins/BaseList";

export default {
  name: "noticeMode",
  mixins: [BaseList],
  components: {
    InfoTable,
  },
  data() {
    return {
      // 遮罩层
      isPersistenceLoading: false,
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示查询条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      sceneList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        messageSceneName: null,
      },

      // 表单校验
      rules: {
        smsTemplateCode: [
          {
            validator: (rule, value, callback) => {
              if (this.form.sms === 0 && value === "") {
                callback(new Error("请选择短信模板"));
              }
              callback();
            },
            trigger: "blur",
          },
        ],
        sysmsgTemplateCode: [
          {
            validator: (rule, value, callback) => {
              if (this.form.sysmsg === 0 && value === "") {
                callback(new Error("请选择系统消息模板"));
              }
              callback();
            },
            trigger: "blur",
          },
        ],
        emailTemplateCode: [
          {
            validator: (rule, value, callback) => {
              if (this.form.email === 0 && value === "") {
                callback(new Error("请选择邮件模板"));
              }
              callback();
            },
            trigger: "blur",
          },
        ],
      },

      //
      sysTemplate: [],
      smsTemplate: [],
      emailTemplate: [],

      // 详情弹框
      isInfoDialog: false,

      info: {
        email: 0,
        sms: 1,
        sysmsg: 0,

        mode: "", // 通知方式

        messageSceneCode: "SCENE_SYSTEM_USER_LOGIN",
        messageSceneId: 1,
        messageSceneName: "主账号登录场景",
        messageSceneRemark: "登录系统时，通过短信或邮件发送登录验证码",

        emailTemplateCode: "EMAIL_TEMPLATE_USER_LOGIN",
        emailTemplateName: "主账号登录邮件模板",

        smsTemplateCode: "",
        smsTemplateName: null,

        isSysMsgTemplate: false, // 20210908需求 SCENE_INSPECT_MANAGE  _HIGH _MIDDLE _LOW 三种场景下需要展示系统消息配置 其他不展示

        sysmsgTemplateCode: "",
        sysmsgTemplateName: null,
      },
      infoMappers: [],

      // 编辑表单
      form: {
        messageSceneId: 1,

        email: 0,
        sms: 1,
        sysmsg: 0,

        messageSceneCode: "SCENE_SYSTEM_USER_LOGIN",

        messageSceneName: "主账号登录场景",
        messageSceneRemark: "登录系统时，通过短信或邮件发送登录验证码",

        emailTemplateCode: "EMAIL_TEMPLATE_USER_LOGIN",
        emailTemplateName: "主账号登录邮件模板",

        smsTemplateCode: "",
        smsTemplateName: null,

        isSysMsgTemplate: false, // 20210908需求 SCENE_INSPECT_MANAGE  _HIGH _MIDDLE _LOW 三种场景下需要展示系统消息配置 其他不展示

        sysmsgTemplateCode: "",
        sysmsgTemplateName: null,
      },
      // 模板
      isTemplateDialog: false,
      templateTitle: "",
      templateInfo: {
        code: "EMAIL_TEMPLATE_USER_LOGIN",
        content:
          '<p><span style="color: rgb(51, 51, 51);">尊敬的 </span><strong style="color: rgb(51, 51, 51);">&amp;{userName}</strong><span style="color: rgb(51, 51, 51);"> ，您好！</span></p><p>\t您正在使用 <strong>&amp;{userCode} </strong>主账号登录&amp;{productName}，本次登录的验证码是 <strong>&amp;{verifyCode}</strong>，请在 <strong>&amp;{validTime} </strong>分钟内进行登录验证。</p><p>\t&amp;{productName}</p><p>\t<span style="color: rgb(51, 51, 51);">江苏保旺达软件技术有限公司</span></p><p>\t<a href="http://www.bwda.net" rel="noopener noreferrer" target="_blank">http://www.bwda.net</a></p><p>\t&amp;{sendDate}</p>',
        createTime: "2019-12-12T00:50:10.000+00:00",
        createUserCode: "somp",
        id: 1,
        name: "主账号登录邮件模板",
        remark:
          "主账号登录验证码的通知邮件，可使用的参数变量&{userCode} 登录的主账号；&{userName}用户姓名；&{verifyCode}登录验证码；&{validTime}验证码有效时长（分钟）；&{productName}产品名称；&{productVersion}产品版本号；&{userPortalAddress}登录门户地址；&{mngtPortalAddress}管理门户地址；&{sendDate}消息发送日期。",
        subject: "&{productName}--系统登录验证",
      },
    };
  },
  created() {
    this.getList();
    this.getSysTemplate();
    this.getSmsTemplate();
    this.getEmailTemplate();
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      queryMessageListByPage(this.queryParams)
        .then((res) => {
          if (res && (res.code === 200 || res.rescode === 200)) {
            this.sceneList = res.data.dataList.reduce((r, c) => {
              r.push(c);
              return r;
            }, []);
            this.total = res.data.totalCount;
          } else {
            this.sceneList = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        messageSceneId: null,
        messageSceneCode: null,
        messageSceneName: null,
        messageSceneRemark: null,
        sms: null,
        smsTemplateCode: null,
        email: null,
        emailTemplateCode: null,
        sysmsg: null,
        sysmsgTemplateCode: null,
      };
      this.resetForm("form");
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (!this.isPersistenceLoading) {
            this.isPersistenceLoading = true;
            updateMessageScene(this.form)
              .then((res) => {
                if (res && (res.code === 200 || res.rescode === 200)) {
                  this.queryParams.pageNum = 1;
                  this.$GlobalSuccessMessage("编辑成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("编辑失败", res.msg);
                }
              })
              .finally(() => {
                this.isPersistenceLoading = false;
              });
          }
        }
      });
    },

    smsChange(label) {
      if (label === 1) {
        this.form.smsTemplateCode = "";
        this.form.smsTemplateName = "";
      }
    },
    sysChange(label) {
      if (label === 1) {
        this.form.sysmsgTemplateCode = "";
        this.form.sysmsgTemplateName = "";
      }
    },
    emailChange(label) {
      if (label === 1) {
        this.form.emailTemplateCode = "";
        this.form.emailTemplateName = "";
      }
    },
    showInfoDialog(row) {
      let mode = [];
      if (row.sms === 0) mode.push("短信");
      if (row.email === 0) mode.push("邮件");
      if (row.sysmsg === 0) mode.push("系统");

      Reflect.ownKeys(this.info).forEach((k) => (this.info[k] = row[k]));
      this.info.mode = mode.join(",");

      console.log("this.info.messageSceneCode: ", this.info.messageSceneCode);
      console.log(this.info.messageSceneCode.indexOf("SCENE_INSPECT_MANAGE"));

      this.info.isSysMsgTemplate =
        this.info.messageSceneCode.indexOf("SCENE_INSPECT_MANAGE") !== -1;

      this.isInfoDialog = true;
    },
    showEditDialog(row) {
      Reflect.ownKeys(this.form).forEach((k) => (this.form[k] = row[k]));
      this.form.sysmsg = row.sysmsg === 0 ? 0 : 1;
      this.form.sms = row.sms === 0 ? 0 : 1;
      this.form.email = row.email === 0 ? 0 : 1;

      this.form.isSysMsgTemplate =
        this.form.messageSceneCode.indexOf("SCENE_INSPECT_MANAGE") !== -1;
      this.open = true;
    },
    getSysTemplate() {
      getSysTemplate().then((res) => {
        if (res && (res.code === 200 || res.rescode === 200)) {
          this.sysTemplate = res.data.dataList;
        } else {
          this.sysTemplate = [];
        }
      });
    },
    getSmsTemplate() {
      getSmsTemplate().then((res) => {
        if (res && (res.code === 200 || res.rescode === 200)) {
          this.smsTemplate = res.data.dataList;
        } else {
          this.smsTemplate = [];
        }
      });
    },
    getEmailTemplate() {
      getEmailTemplate().then((res) => {
        if (res && (res.code === 200 || res.rescode === 200)) {
          this.emailTemplate = res.data.dataList;
        } else {
          this.emailTemplate = [];
        }
      });
    },
    showSmsTemplate() {
      this.templateTitle = "短信";
      let template = this.smsTemplate.find(
        (item) => item.code === this.form.smsTemplateCode
      );
      this.setTemplateDialogData(template);
    },
    showSysTemplate() {
      this.templateTitle = "系统";
      let template = this.sysTemplate.find(
        (item) => item.code === this.form.sysmsgTemplateCode
      );
      this.setTemplateDialogData(template);
    },
    showEmailTemplate() {
      this.templateTitle = "邮件";

      let template = this.emailTemplate.find(
        (item) => item.code === this.form.emailTemplateCode
      );
      this.setTemplateDialogData(template);
    },
    setTemplateDialogData(template) {
      if (template) {
        Reflect.ownKeys(this.templateInfo).forEach(
          (k) => (this.templateInfo[k] = template[k])
        );
      } else {
        Reflect.ownKeys(this.templateInfo).forEach(
          (k) => (this.templateInfo[k] = "")
        );
      }
      this.isTemplateDialog = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.info-table {
  display: flex;
  flex-wrap: wrap;

  .info-row {
    min-height: 39px;
    display: flex;
    border-top: 1px solid rgb(232, 232, 232);
    width: 100%;

    &:last-child {
      border-bottom: 1px solid rgb(232, 232, 232);
    }

    .info-label {
      width: 160px;
      height: 100%;
      line-height: 39px;
      background-color: #f5f5f5;
      text-align: right;
      padding-right: 8px;
      box-sizing: border-box;
    }

    .info-value {
      height: 100%;
      width: calc(100% - 160px);
      line-height: 39px;
      padding-left: 8px;
      box-sizing: border-box;
    }
  }
}
.el-tag--danger {
  background-color: #ecf5ff;
  color: #409eff;
  border: 1px solid #d9ecff;
}
</style>
